<!--
 * @name order
 * @description 组件描述
 * @author idouya
 * @email elegentfrog@163.com
 * @date 2025-07-02
 -->

<template>
  <div class="p-score common-bg common-layout">
    <page-title
      :discipline="gameInfo.discipline"
      :event="gameInfo.event"
      :match="gameInfo.match"
      :type="gameInfo.type"
      :eventName="gameInfo.eventName"
      :startTime="gameInfo.startTime"
    ></page-title>
    <div class="content">
      <div class="top">
        <div class="top-left">
          <div class="left-item">
            <div class="label bg">障碍罚分</div>
            <div class="value bg">{{ scoreObj.ObstaclePunish }}</div>
          </div>
          <div class="left-item">
            <div class="label bg">时间罚分</div>
            <!-- <div class="value bg">{{ scoreObj.TimePunish }}</div> -->
            <div class="value bg">
              {{
                getTimePunish % 1 !== 0
                  ? getTimePunish.toFixed(1)
                  : PunishTimeUnit % 1 !== 0 && getTimePunish > 0
                  ? getTimePunish.toFixed(1)
                  : getTimePunish
              }}
            </div>
            <!-- getTimePunish -->
          </div>
          <div class="left-item">
            <div class="label bg">本轮罚分</div>
            <div class="value bg">
              {{
                (scoreObj.ObstaclePunish + getTimePunish) % 1 !== 0
                  ? (scoreObj.ObstaclePunish + getTimePunish).toFixed(1)
                  : PunishTimeUnit % 1 !== 0 && scoreObj.ObstaclePunish + getTimePunish > 0
                  ? (scoreObj.ObstaclePunish + getTimePunish).toFixed(1)
                  : scoreObj.ObstaclePunish + getTimePunish
              }}
            </div>
          </div>
          <div class="left-item" v-if="scoreInfo.IsAddResult == 1">
            <div class="label bg">上轮罚分</div>
            <div class="value bg">{{ scoreObj.LastRoundPunish }}</div>
          </div>
          <div class="left-item" v-if="postFlag == 1 && scoreInfo.IsAddResult == 1">
            <div class="label bg">总罚分</div>
            <div class="value bg">{{ scoreObj.TwoRoundsPunish }}</div>
          </div>
        </div>
        <div class="top-right">
          <div class="athelete">
            <div class="order common">{{ scoreInfo.Order }}</div>
            <div class="name common">
              {{ scoreInfo.AthleteName }}
            </div>
            <div class="rank common" v-show="scoreInfo.Rank">当前排名</div>
          </div>
          <div class="horse">
            <div class="order horseOrder common">{{ scoreInfo.HorseOrder }}</div>
            <div
              :style="scoreInfo?.HorseName?.length > 18 ? 'font-size: 2rem !important;' : ''"
              :class="['name', 'common', scoreInfo?.HorseName?.length > 15 ? 'horseNameAdapt' : '']"
            >
              {{ scoreInfo.HorseName }}
            </div>
            <div class="rank common" v-show="scoreInfo.Rank">{{ scoreInfo.Rank }}</div>
          </div>
          <div class="score-info">
            <div class="info-left">
              <div class="club">{{ scoreInfo.CountryName }}</div>
              <div class="score">
                {{
                  isRunning && curStatus == 's1'
                    ? TimeLimited <= runTime
                      ? floorToFixed(TimeLimited, 1)
                      : Number(runTime)?.toFixed(1)
                    : curStatus == 's0'
                    ? runTimeResult
                    : TimeLimited <= runTime
                    ? floorToFixed(TimeLimited, 1)
                    : runTime
                }}
              </div>
            </div>
            <div class="info-right">
              <div class="allow-time" v-show="scoreInfo.AllowTime">
                允许时间：{{ scoreInfo.AllowTime }}秒
              </div>
              <div class="correction-time" v-show="scoreInfo.RedressTime">
                校正时间：+{{ scoreInfo.RedressTime }}秒
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="bottom">
        <div class="bottom-item" v-for="(item, index) in rankList" :key="index">
          <div class="rank" :style="!item.Rank ? 'opacity: 0' : ''">{{ item.Rank }}</div>
          <div class="rank-info">
            <div class="name">{{ item.AthleteName }}</div>
            <div
              :style="item?.HorseName?.length > 18 ? 'font-size: 2.1rem !important;' : ''"
              :class="['horseName', item?.HorseName?.length > 15 ? 'horseNameAdapt' : '']"
            >
              {{ item.HorseName }}
            </div>
            <div class="club">{{ item.CountryName }}</div>
            <div class="score score-center" v-if="/[A-Z]/.test(item.RoundPunish)">
              {{ item.RoundPunish }}
            </div>
            <div
              class="score"
              :class="/[A-Z]/.test(item.TwoRoundsPunish) ? 'score-center' : ''"
              v-else
            >
              <template v-if="/[A-Z]/.test(item.TwoRoundsPunish)">
                {{ item.TwoRoundsPunish }}
              </template>
              <template v-else>
                ({{ item.TwoRoundsPunish }} - {{ floorToFixed(item.Time, 2) }})
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import useStore from '@/store'
import Storage from '@/assets/js/storage'
import Utils from '@/assets/js/utils'
import Config from '@/assets/js/config'
import PageTitle from '@/components/scb/PageTitle.vue'
import { useMultiProcRequest } from '@/assets/js/useMultiProcRequest'
import { computed, ref } from 'vue'

const { formatToFixed2, results, fetchForProcs } = useMultiProcRequest()

const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()

const gameInfo = ref({
  discipline: '马术',
  match: '',
  event: 'JUMPTEAM',
  type: '实时成绩',
  eventName: '',
})

const scoreObj = ref({
  ObstaclePunish: 0,
  TimePunish: 0,
  RoundPunish: 0,
  LastRoundPunish: 0,
  TwoRoundsPunish: 0,
})

const PunishTimeNum = ref(1)
const PunishTimeUnit = ref(1)
const TimeLimited = ref(0)

const runTime = ref(0)
const runTimeResult = ref(45)
const time0 = ref(0)
const time1 = ref(0)
const isRunning = ref(false)
const isRunning2 = ref(false)

const getTimePunish = computed(() => {
  let runTimeData = runTime.value
  if (runTime.value >= TimeLimited.value) {
    runTimeData = TimeLimited.value
  }
  if (isRunning.value && parseFloat(runTimeData) >= scoreInfo.value.AllowTime) {
    return (
      Math.ceil((Math.ceil(runTimeData) - scoreInfo.value.AllowTime) / PunishTimeNum.value) *
      PunishTimeUnit.value
    )
  } else {
    return scoreObj.value.TimePunish
  }
})

const scoreTypeList = reactive([
  { label: '障碍罚分', code: 'ObstaclePunish', value: 0 },
  { label: '时间罚分', code: 'TimePunish', value: 0 },
  { label: '本轮罚分', code: 'RoundPunish', value: 0 },
  { label: '上轮罚分', code: 'LastRoundPunish', value: 0 },
  { label: '两轮罚分', code: 'TwoRoundsPunish', value: 0 },
])

const scoreList = ref([])

const scoreInfo = ref({})

const rankList = ref([])

const params = ref({})
const procName = ref([])
const commonStore = useStore.useCommonStore()
const baseRunTime = ref(0)
const hasStartedOnce = ref(false)
const postFlag = ref(null)

let timer1 = null
let timer2 = null
const TIMEOUT_MS = 45000

let pastRunTimeMs = 0 // 之前已经运行了多少毫秒
let startTimeMs = 0 // 本轮开始时间戳（毫秒）

const curStatus = ref(null)

onUnmounted(() => {
  clearInterval(timer1)
  clearInterval(timer2)
})

onMounted(async () => {
  init()
})

const init = async () => {
  clearInterval()
  params.value = route.query
  procName.value = Config.procNameList[route.name]
  await getData()
  const lastMsg = commonStore.receivedActionMessages?.slice(-1)[0]
  if (lastMsg && lastMsg.tplCode == 'scb-jump-score') {
    handleMessage(lastMsg)
  }
  startTimer()
  startTimer2()
}

const getData = async () => {
  if (procName.value.length > 0) {
    await fetchForProcs(procName.value, {
      procName: procName.value[0],
      keyValues: params.value,
    })
  }
}

// 运行时间计时器
const startTimer = () => {
  // 如果已有定时器，先清掉
  if (timer1) {
    clearInterval(timer1)
    timer1 = null
  }
  timer1 = setInterval(() => {
    if (isRunning.value) {
      time1.value = new Date().getTime()
      const tempRunTime = baseRunTime.value + (time1.value - time0.value) / 1000
      runTime.value = Math.floor(tempRunTime * 100) / 100
    }
    if (TimeLimited.value <= runTime.value) {
      clearInterval(timer1)
      timer1 = null
    }
  }, 20)
}

const startTimer2 = () => {
  timer2 = setInterval(() => {
    if (isRunning2.value && runTimeResult.value > 0) {
      const now = new Date().getTime()
      const totalElapsed = pastRunTimeMs + (now - startTimeMs)
      const remainingMs = TIMEOUT_MS - totalElapsed
      runTimeResult.value = (remainingMs / 1000).toFixed(0)
      if (runTimeResult.value.length > 6) {
        console.log('-------------------------')
        console.log(runTimeResult)
      }
    }
  }, 20)
}

const floorToFixed = (num, decimals = 2) => {
  const numStr = num.toString()
  const decimalIndex = numStr.indexOf('.')
  if (numStr.length === 0) {
    return '0'
  }
  if (decimalIndex === -1) {
    return num + '.00' // 整数直接补零
  }

  // 直接截取所需小数位
  const truncatedStr = numStr.substring(0, decimalIndex + decimals + 1)
  return parseFloat(truncatedStr).toFixed(decimals)
}

const handleMessage = (msg) => {
  const data = msg?.data
  postFlag.value = null
  if (!data) return
  if (data?.status == 1) {
    // 正计时进行中
    curStatus.value = 's1'
    isRunning2.value = false
    baseRunTime.value = data?.runTime
    if (!hasStartedOnce.value) {
      runTime.value = 0
      time0.value = new Date().getTime()
      hasStartedOnce.value = true
    } else {
      // 继续运行：修正 time0，避免 runTime 增加错位
      time0.value = new Date().getTime()
    }
    isRunning.value = true
    scoreObj.value.ObstaclePunish = data.penPoint
    scoreObj.value.TimePunish = Math.ceil(data.penTime / PunishTimeNum.value) * PunishTimeUnit.value
    scoreObj.value.RoundPunish =
      Math.ceil(data.penTime / PunishTimeNum.value) * PunishTimeUnit.value + data.penPoint
    scoreInfo.value.RedressTime = data.redressTime || 0
  } else if (data?.status == 2) {
    // 正计时暂停
    curStatus.value = 's1'
    isRunning2.value = false
    isRunning.value = false
    baseRunTime.value = runTime.value
    scoreObj.value.ObstaclePunish = data.penPoint
    scoreObj.value.TimePunish = Math.ceil(data.penTime / PunishTimeNum.value) * PunishTimeUnit.value
    scoreObj.value.RoundPunish =
      Math.ceil(data.penTime / PunishTimeNum.value) * PunishTimeUnit.value + data.penPoint
    scoreInfo.value.RedressTime = data.redressTime || 0
    // runTime.value = Math.floor(data.runTime * 10) / 10
    runTime.value = floorToFixed(data.runTime, 2)
  } else if (data?.status == 0) {
    curStatus.value = 's0'
    isRunning.value = false
    if (data?.status0 == 1) {
      // 0: 45秒倒计时未开始
      // 1: 45秒倒计时进行中
      // 2: 45秒倒计时暂停
      // 3: 45秒倒计时结束
      // isRunning.value = false
      startTimeMs = new Date().getTime()
      pastRunTimeMs = data.runTime // 假设单位是秒
      isRunning2.value = true
    } else {
      if (data.status0 == 0 && data.runTime == 0) {
        getData()
        scoreObj.value.ObstaclePunish = data.penPoint || 0
        scoreObj.value.TimePunish =
          Math.ceil(data.penTime / PunishTimeNum.value) * PunishTimeUnit.value || 0
        scoreInfo.value.RedressTime = data.redressTime || 0
      }
      isRunning2.value = false
      pastRunTimeMs = data.runTime
      runTimeResult.value = (45 - data.runTime / 1000).toFixed(0)
      if (data?.status0 == 3 && data.runTime == 45000) {
        runTime.value = 0
      } else {
        runTime.value = floorToFixed(0.001 * data.runTime, 1)
      }
    }
  } else if (data?.status == 3) {
    // 正计时结束
    curStatus.value = 's1'
    isRunning2.value = false
    isRunning.value = false
    hasStartedOnce.value = false
    baseRunTime.value = 0
    runTime.value = floorToFixed(data.runTime, 2)
    scoreObj.value.ObstaclePunish = data.penPoint
    scoreObj.value.TimePunish = Math.ceil(data.penTime / PunishTimeNum.value) * PunishTimeUnit.value
    scoreObj.value.RoundPunish =
      Math.ceil(data.penTime / PunishTimeNum.value) * PunishTimeUnit.value + data.penPoint
    scoreInfo.value.RedressTime = data.redressTime || 0
    postFlag.value = data.postFlag
    if (data.postFlag == 1) {
      // runTime.value = data.runTime
      getData()
    }
  }
}

watchEffect(() => {
  if (results.value?.datasetList?.length) {
    const data = results.value.datasetList[0][0]
    gameInfo.value.event = data?.EventCode
    gameInfo.value.match = data?.MatchName
    gameInfo.value.eventName = data?.EventName
    rankList.value = results.value.datasetList[1].slice(0, 3) || []
    // scoreInfo.value = results.value.datasetList[0][0] || {}
    scoreInfo.value = {
      ...scoreInfo.value,
      Order: data?.Order,
      Rank: data?.Rank || 0,
      Total: data?.Total,
      LastRoundPunish: data?.LastRoundPunish,
      TwoRoundsPunish: data?.TwoRoundsPunish,
      AthleteName: data?.AthleteName,
      CountryName: data?.CountryName,
      DisciplineName: data?.DisciplineName,
      EventCode: data?.EventCode,
      EventName: data?.EventName,
      HorseName: data?.HorseName,
      HorseOrder: data?.HorseOrder,
      LastRoundPunish: data?.LastRoundPunish,
      MatchName: data?.MatchName,
      AllowTime: data?.AllowTime,
      IsAddResult: data?.IsAddResult,
    }
    PunishTimeNum.value = data?.m || 1
    PunishTimeUnit.value = data?.n || 1
    TimeLimited.value = parseInt(data?.TimeLimited)

    Object.keys(scoreObj.value).forEach((key) => {
      //     ObstaclePunish: 0,
      // TimePunish: 0,
      // RoundPunish: 0,
      if (!['ObstaclePunish', 'TimePunish', 'RoundPunish'].includes(key)) {
        scoreObj.value[key] = results.value.datasetList[0][0][key] || 0
      }
    })
    // runTime.value = formatToFixed2(results.value.datasetList[0][0]?.Time) || 0
  }
})

watch(
  () => route.query,
  (val) => {
    params.value = val
    init()
  }
)

watch(
  () => commonStore.receivedActionMessages,
  (newVal, oldVal) => {
    if (newVal.length > 0) {
      const latestMsg = newVal[newVal.length - 1]
      handleMessage(latestMsg)
    }
  },
  { deep: true }
)
</script>

<style scoped lang="scss">
@import '@/assets/scss/scb/score';
.score-center {
  text-align: center;
}
</style>
